<?php

/*
 * @Date: 2025-08-18 00:03:13
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-10-28 22:09:02
 * @FilePath: /admin-api/app/Http/Controllers/AuthController.php
 */

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        Validator::make($request->input(), [
            'username' => ['required', 'exists:users,username'],
            'password' => ['required'],
        ])->validate();

        $user = User::where('username', $request->username)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            $user->login_count++;
            $user->save();

            return $this->success('登录成功', ['token' => $user->createToken('auth')->plainTextToken, 'user' => $user]);
        }

        throw ValidationException::withMessages(['password' => '密码输入错误']);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return $this->success('退出成功');
    }

    //获取当前登录用户信息
    public function user(Request $request)
    {
        return $this->success('', $request->user());
    }

    public function password(Request $request)
    {
        Validator::make($request->input(), [
           'old_password' => ['required'],
           'password' => ['required', 'confirmed'],
        ])->validate();

        $user = $request->user();

        if (!Hash::check($request->old_password, $user->password)) {
            throw ValidationException::withMessages(['password' => '密码输入错误']);
        }

        $user->password = Hash::make($request->password);
        $user->save();

        return $this->success('修改密码成功');
    }
}
